package com.example.osstest.demo;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.UUID;

@RestController
@RequestMapping("/")
public class OSSController {

    private String host="";  // http://saifu-oss.oss-cn-shanghai.aliyuncs.com
    private String EndPoint =""; // oss-cn-shanghai.aliyuncs.com
    private String AccessKeyID ="";
    private String AccessKeySecret ="";


    @GetMapping("oss")
    public ResponseEntity<OSSPolicyDTO> getPolicy() throws UnsupportedEncodingException {
        final OSSPolicyDTO ossPolicyDTO = new OSSPolicyDTO();
        OSSClient ossClient = new OSSClient(EndPoint, AccessKeyID, AccessKeySecret);


        String key = String.format("users/%s", UUID.randomUUID().toString());
        Date expiration = getExpiration(1);

        PolicyConditions policyConditions = new PolicyConditions();
        policyConditions.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 999999);
        policyConditions.addConditionItem(MatchMode.Exact, PolicyConditions.COND_KEY, key);

        String policy = ossClient.generatePostPolicy(expiration, policyConditions);
        byte[] binaryData = policy.getBytes(StandardCharsets.UTF_8);

        ossPolicyDTO.setAccessId(AccessKeyID);
        ossPolicyDTO.setPolicy(BinaryUtil.toBase64String(binaryData));
        ossPolicyDTO.setSignature(ossClient.calculatePostSignature(policy));
        ossPolicyDTO.setKey(key);
        ossPolicyDTO.setHost(host);
        ossPolicyDTO.setExpire(String.valueOf(expiration.getTime() / 1000));
        ossClient.shutdown();


        return ResponseEntity.ok(ossPolicyDTO);
    }

    private Date getExpiration(int s) {
        long expireTime = 60 * s;
        long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
        return new Date(expireEndTime);
    }
}
